package com.sgb.kjwl.viewmodel.manage;

import android.content.Context;
import android.util.Log;
import android.view.View;

import androidx.databinding.ObservableField;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.sdk.android.vod.upload.VODUploadCallback;
import com.alibaba.sdk.android.vod.upload.VODUploadClientImpl;
import com.alibaba.sdk.android.vod.upload.model.UploadFileInfo;
import com.alibaba.sdk.android.vod.upload.model.VodInfo;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.view.entity.AliProofEntity;
import com.sgb.link.entity.PickFilterEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.manage.WebsiteInfoEntity;
import com.sgb.kjwl.repository.ManageRepertory;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteUpDataQiYeXiXinActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class WebsiteUpDataQiYeXiXinModel extends BaseViewModel {
    public MutableLiveData<List<PickFilterEntity<List<PickFilterEntity>>>> businessType = new MutableLiveData<>();
    private WebsiteUpDataQiYeXiXinActivity activity;
    private ManageRepertory repertory;
    private final VODUploadClientImpl mUploadClient;
    private AliProofEntity mProofEntity;

    public ObservableField<WebsiteInfoEntity> entity = new ObservableField<>(new WebsiteInfoEntity());

    public MutableLiveData<List<WebsiteInfoEntity.ServiceAreaEntity>> serviceAreas = new MutableLiveData<>();
    public MutableLiveData<List<WebsiteInfoEntity.ServiceAreaEntity>> serviceAreas1 = new MutableLiveData<>();

    public WebsiteUpDataQiYeXiXinModel(WebsiteUpDataQiYeXiXinActivity activity, ManageRepertory repertory) {
        this.activity = activity;
        this.repertory = repertory;
        mUploadClient = new VODUploadClientImpl(activity.getApplicationContext());
    }

    //经营类型
    public void getBusinessType1() {
        APIManager.getInstance().getBusinessManagementAPI().getNewServiceType(0).enqueue(new ICallBack<BaseEntity<List<PickFilterEntity<List<PickFilterEntity>>>>>(true, true) {
            @Override
            public void onSuccess(BaseEntity<List<PickFilterEntity<List<PickFilterEntity>>>> data) {
                if (data != null && data.getData() != null){
                    businessType.postValue(data.getData());
                }

            }
        });
    }
    //-----网站信息新增/编辑----------------------------------------------------------------
    public void setWebsiteInfo() {
        if (activity != null) {
            DialogHelper.showProgressDialog(activity, null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        }
        APIManager.getInstance().getWebsiteInfoAPI().setWebsiteInfo(entity.get()).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data != null){
                    activity.editWebsiteInfo();
                }
            }
            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                super.onFailure(call, t);
                MToast.showToast(activity, "onError！" + t.getMessage());
            }
        });
    }

    //-----网站详情----------------------------------------------------------------
    public void getWebsiteInfo(String siteNo, int siteType) {
        if (activity != null) {
            DialogHelper.showProgressDialog(activity, null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        }
        Map<String, String> map = new HashMap();
        map.put("siteNo", siteNo);
        map.put("siteType", siteType + "");
        APIManager.getInstance().getWebsiteInfoAPI().getSiteInfo(map).enqueue(new ICallBack<BaseEntity<WebsiteInfoEntity>>() {

            @Override
            public void onSuccess(BaseEntity<WebsiteInfoEntity> data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    activity.showWebsiteInfo(data.getData());
                }
            }
        });
    }

    // -----上传相册照片---------------------------------------------------------------------------
    public void uploadAvatarFileModel(File file, int completeNum) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + completeNum + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(activity, null, "头像上传中" + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                if (response.body() == null || response.body().getState() == null) {
                    MToast.showToast(activity, "上传失败！");
                    DialogHelper.dismissProgressDialog();
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.uploadAvatarResult(response.body().getData().toString());
                } else {
                    MToast.showToast(activity, "上传失败！");
                    DialogHelper.dismissProgressDialog();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, "上传失败！" + t.getMessage());
            }
        });
    }

    // -----行业分类---------------------------------------------------------------------------
    private OptionsPickerView<PickSelectEntity> mIndustryOptions;
    private List<PickSelectEntity<List<PickSelectEntity>>> mOpt;
    private List<PickSelectEntity> mOpt1 = new ArrayList<>();//行业分类1
    private List<List<PickSelectEntity>> mOpt2 = new ArrayList<>();//行业分类2
    private int opt1;
    private int opt2;

    public void getIndustryCategoryAll(boolean isShow) {
        DialogHelper.showProgressDialog(activity, null, "数据获取中" + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getWebsiteInfoAPI().getIndustryCategoryAll().enqueue(new Callback<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> call, Response<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mOpt = response.body().getData();
                    if (mOpt == null || mOpt.size() == 0) {
                        return;
                    }
                    mOpt = response.body().getData();
                    mOpt1.clear();
                    mOpt1.addAll(mOpt);
                    mOpt2.clear();
                    for (PickSelectEntity<List<PickSelectEntity>> provinceDatum : mOpt) {
                        if (provinceDatum.getChildren() != null){
                            List<PickSelectEntity> children = provinceDatum.getChildren();
                            mOpt2.add(children);
                        }else {
                            mOpt2.add(new ArrayList<PickSelectEntity>());
                        }

                    }
                    if (isShow) {
                        showIndustryPop();
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, "onError！" + t.getMessage());
            }
        });
    }

    public void showIndustryPop() {
        if (mOpt1 == null || mOpt1.size() == 0) {
            getIndustryCategoryAll(true);
            return;
        }
        if (mIndustryOptions == null) {
            mIndustryOptions = new OptionsPickerBuilder(activity, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    if (mOpt2.get(options1).size() == 0){
                        MToast.showToast(activity, "请选择行业分类");
                        return;
                    }
                    activity.selectedIndustry(mOpt.get(options1), mOpt2.get(options1).get(options2));
                    opt1 = options1;
                    opt2 = options2;
                }
            }).setCancelText("取消").setSubCalSize(15)
                    .setCancelColor(activity.getResources().getColor(R.color.color_tab_two))
                    .setSubmitText("确定")
                    .setSubmitColor(activity.getResources().getColor(R.color.color_main)).build();
            mIndustryOptions.setTitleText("行业分类");
        }
        mIndustryOptions.setPicker(mOpt1, mOpt2);
        mIndustryOptions.setSelectOptions(opt1, opt2);
        mIndustryOptions.show();
    }

    // -----企业性质---------------------------------------------------------------------------
    public void getFindEnabledList() {
        DialogHelper.showProgressDialog(activity, null, "数据获取中" + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getWebsiteInfoAPI().getFindEnabledList().enqueue(new Callback<BaseEntity<List<PickFilterEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickFilterEntity>>> call, Response<BaseEntity<List<PickFilterEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.showCompanyNature(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickFilterEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, "onError！" + t.getMessage());
            }
        });
    }

    //服务范围
    public void getCompanyServiceScope(){
        DialogHelper.showProgressDialog(activity, null, "数据获取中" + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getWebsiteInfoAPI().getServiceArea().enqueue(new ICallBack<BaseEntity<List<WebsiteInfoEntity.ServiceAreaEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<WebsiteInfoEntity.ServiceAreaEntity>> data) {
                if (data != null && data.getData() != null){
                    serviceAreas.postValue(data.getData());
                }
            }
        });
    }
    //经营模式
    public void getBusinessModule(int type){
        DialogHelper.showProgressDialog(activity, null, "数据获取中" + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getWebsiteInfoAPI().getBusinessModule(type).enqueue(new ICallBack<BaseEntity<List<WebsiteInfoEntity.ServiceAreaEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<WebsiteInfoEntity.ServiceAreaEntity>> data) {
                if (data != null && data.getData() != null){
                    serviceAreas1.postValue(data.getData());
                }
            }
        });
    }

    // -----企业月产量--------------------------------------------------------------------------
    public void getFindUnitList() {
        DialogHelper.showProgressDialog(activity, null, "数据获取中" + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getWebsiteInfoAPI().getFindUnitList().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.showCompanyUnit(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, "onError！" + t.getMessage());
            }
        });
    }

    // -----年营业额--------------------------------------------------------------------------
    public void getTurnover() {
        List<PickSelectEntity> list = new ArrayList<>();
        list.add(new PickSelectEntity("0", "10万以下"));
        list.add(new PickSelectEntity("1", "10~30万元"));
        list.add(new PickSelectEntity("2", "30~50万元"));
        list.add(new PickSelectEntity("3", "50~100万元"));
        list.add(new PickSelectEntity("4", "500~1000万元"));
        list.add(new PickSelectEntity("5", "1000~5000万元"));
        list.add(new PickSelectEntity("6", "5000~1亿"));
        list.add(new PickSelectEntity("7", "1亿以上"));
        activity.showTurnover(list);
    }

    // -----信息简介--------------------------------------------------------------------------
    public void getIsProcessing() {
        List<PickSelectEntity> list = new ArrayList<>();
        list.add(new PickSelectEntity("0", "否"));
        list.add(new PickSelectEntity("1", "是"));
        activity.showIsProcessing(list);
    }

    // -----质量控制--------------------------------------------------------------------------
    public void getQualityControl() {
        List<PickSelectEntity> list = new ArrayList<>();
        list.add(new PickSelectEntity("0", "内部"));
        list.add(new PickSelectEntity("1", "第三方"));
        activity.showQualityControl(list);
    }

    // -----业务类型--------------------------------------------------------------------------
    public void getBusinessType() {
        List<PickSelectEntity> list = new ArrayList<>();
        list.add(new PickSelectEntity("0", "生产型"));
        list.add(new PickSelectEntity("1", "研发型"));
        list.add(new PickSelectEntity("2", "贸易型"));
        list.add(new PickSelectEntity("3", "服务型"));
        list.add(new PickSelectEntity("4", "批发型"));
        list.add(new PickSelectEntity("5", "零售型"));
        activity.showBusinessType(list);
    }

    // -----管理体系认证--------------------------------------------------------------------------
    public void getManageAuthList() {
        DialogHelper.showProgressDialog(activity, null, "数据获取中" + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getWebsiteInfoAPI().getManageAuthsList().enqueue(new ICallBack<BaseEntity<List<PickFilterEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<PickFilterEntity>> data) {
                if (data == null || data.getState() == null)
                    return;
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    activity.showCompanyAuth(data.getData());
                }
            }
        });
    }

    // -----市场区域--------------------------------------------------------------------------
    public void getMarketArea() {
        DialogHelper.showProgressDialog(activity, null, "数据获取中" + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getWebsiteInfoAPI().getMarketArea().enqueue(new Callback<BaseEntity<BaseEntity<List<PickFilterEntity<List<PickFilterEntity>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<BaseEntity<List<PickFilterEntity<List<PickFilterEntity>>>>>> call, Response<BaseEntity<BaseEntity<List<PickFilterEntity<List<PickFilterEntity>>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.showMarketArea(response.body().getData().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<BaseEntity<List<PickFilterEntity<List<PickFilterEntity>>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, "onError！" + t.getMessage());
            }
        });
    }

    // -----获取视频---------------------------------------------------------------------------

    public void videoSelector(int number, int requestCode) {
        PictureSelector.create(activity)
                .openGallery(PictureMimeType.ofVideo())
                .imageEngine(GlideEngine.createGlideEngine())
                .selectionMode(PictureConfig.MULTIPLE)
                .isCompress(true)//是否压缩
                .minimumCompressSize(10240)//小于10M不压缩
                .maxSelectNum(number)//判断还能选多少张图片
                .forResult(requestCode);
    }

    //获取视频上传凭证
    public void getVideoParamsSTS(String path) {
        DialogHelper.showProgressDialog(activity, null, "视频处理中" + "...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        APIManager.getInstance().getWebsiteInfoAPI().getVideoParams(map).enqueue(new Callback<BaseEntity<AliProofEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<AliProofEntity>> call, Response<BaseEntity<AliProofEntity>> response) {
                if (response.body().getState().equals("ok")) {
                    mProofEntity = response.body().getData();
                    VodInfo vodInfo = new VodInfo();
                    vodInfo.setTitle("");
                    vodInfo.setDesc("");
                    vodInfo.setCateId((int) System.currentTimeMillis());
                    vodInfo.setTags(null);
                    mUploadClient.addFile(path, vodInfo);
                    //阿里凭证
                    mUploadClient.init(mUploadCallback);
                    mUploadClient.start();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<AliProofEntity>> call, Throwable t) {
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    VODUploadCallback mUploadCallback = new VODUploadCallback() {
        public void onUploadSucceed(UploadFileInfo info) {
            Log.e("onUploadSucceed", "onUploadSucceed");
            activity.uploadVideoResult(mProofEntity.getVideoId(), info);
        }

        public void onUploadFailed(UploadFileInfo info, String code, String message) {
            Log.e("onUploadFailed", "onUploadFailed code = " + code + "  message == " + message);
        }

        public void onUploadProgress(UploadFileInfo info, long uploadedSize, long totalSize) {
            Log.e("onUploadFailed", "onUploadFailed");
        }

        public void onUploadTokenExpired() {
            Log.e("onUploadTokenExpired", "onUploadTokenExpired");
            mUploadClient.resumeWithAuth(mProofEntity.getUploadAuth());
        }

        public void onUploadRetry(String code, String message) {
            Log.e("onUploadRetry", "onUploadRetry");
        }

        public void onUploadRetryResume() {
            Log.e("onUploadRetryResume", "onUploadRetryResume");
        }

        public void onUploadStarted(UploadFileInfo uploadFileInfo) {
            Log.e("onUploadStarted", "onUploadStarted");
            mUploadClient.setUploadAuthAndAddress(uploadFileInfo, mProofEntity.getUploadAuth(), mProofEntity.getUploadAddress());
        }
    };

    // -----经营模式---------------------------------------------------------------------------
    public void getBusinessModel() {
        DialogHelper.showProgressDialog(activity, null, "数据获取中" + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getWebsiteInfoAPI().getBusinessModel().enqueue(new Callback<BaseEntity<List<PickFilterEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickFilterEntity>>> call, Response<BaseEntity<List<PickFilterEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.showBusinessMode(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickFilterEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, "onError！" + t.getMessage());
            }
        });
    }

    /**
     * 根据路由获取H5链接访问
     *
     * @param mContext
     * @param body     传入的参数
     * @param param    路由地址
     * @param code     返回的Code码
     */
    public void getH5Url(Context mContext, String body, String param, int code, String title) {
        DialogHelper.showProgressDialog(mContext, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getUrlSetting(param).enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data == null || data.getState() == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    String url = data.getData().getUrl() + "?title=" + title;
                    WebViewX5HostActivity.start(mContext, url, body, code);
                } else {
                    MToast.showToast(mContext, data.getMsg());
                }
            }
        });
    }

    // -----备案单位---------------------------------------------------------------------------
    public void getProvinceRecordUnit() {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getWebsiteInfoAPI().getProvinceRecordUnit().enqueue(new Callback<BaseEntity<List<PickFilterEntity<List<PickFilterEntity>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickFilterEntity<List<PickFilterEntity>>>>> call, Response<BaseEntity<List<PickFilterEntity<List<PickFilterEntity>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.showRecordUnit(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickFilterEntity<List<PickFilterEntity>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, "onError！" + t.getMessage());
            }
        });
    }
}
